<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
var echarts = require('echarts/lib/echarts')
// 引入 ECharts 主模块
require('echarts/lib/chart/pie')
// 引入提示框和标题组件
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')
require('echarts/lib/component/legend')
// require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/utils'
import { themeColor } from '@/assets/echarts/theme'

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '210px'
    },
    statistics: {
      type: Object,
      default: () => ({})
    },
    echartItem: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    'echartItem': function() {
      this.initChart()
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.chart.setOption({
        color: themeColor,
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} '
        },
        legend: {
          orient: 'vertical',
          show: false
        },
        series: [
          {
            name: '',
            type: 'pie',
            radius: '55%',
            center: ['50%', '50%'],
            data: this.handleArr(this.echartItem),
            labelLine: {
              legend: 4,
              length2: 4
            }
          }
        ]
      })
    },
    handleArr(list) {
      return Object.keys(list).map(ele => {
        return {
          value: list[ele],
          name: ele
        }
      })
    }
  }
}
</script>
